from sqlmodel import Field, SQLModel
from datetime import datetime
from app.core.utils import cents_to_yuan_str
from pydantic import field_serializer, computed_field, field_validator

class MonitorBuyBase(SQLModel):
    """用户购买监控表基础模型"""
    archiveId: int = Field(default=0, index=True, description="用户藏品ID")
    archiveName: str = Field(default="", max_length=128, description="用户藏品名称")
    archiveImg: str = Field(default="", max_length=255, description="用户藏品图片URL")
    platformId: int = Field(default=0, description="藏品发行平台ID")
    buyPrice: int = Field(default=0, description="买入价格（分）")
    maxBuyNum: int = Field(default=0, description="购买数量")
    boughtNum: int = Field(default=0, description="已购买数量")
    status: int = Field(default=0, description="状态：0-监控中，1-已完成 2-已取消")
    days: int = Field(default=0, description="监控天数")
    expireAt: datetime = Field(default_factory=datetime.now, description="过期时间戳")
    pauseRemark: str = Field(default="", max_length=255, description="暂停备注")

class MonitorBuyCreate(MonitorBuyBase):
    """用户购买监控表创建模型"""
    uid: int = Field(default=0, index=True, description="用户ID")
    nickname: str = Field(default="", max_length=128, description="用户昵称")
    
class MonitorBuyCreateReq(SQLModel):
    """用户购买监控表创建请求模型"""
    archiveId: int = Field(default=0, index=True, description="用户藏品ID")
    archiveName: str = Field(default="", max_length=128, description="用户藏品名称")
    archiveImg: str = Field(default="", max_length=255, description="用户藏品图片URL")
    platformId: int = Field(default=0, description="藏品发行平台ID")
    buyPrice: str = Field(default="0.0", description="买入价格（元）")
    maxBuyNum: int = Field(default=0, description="购买数量")
    days: int = Field(default=3, description="监控天数")

class MonitorBuyOut(MonitorBuyBase):
    """用户购买监控表输出模型"""
    id: int = Field(default=0, description="监控购买ID", exclude=True) # 数据库主键，不返回给客户端
    createdAt: datetime = Field(default_factory=datetime.now, description="创建时间戳", exclude=True) # 数据库创建时间，不返回给客户端

    @computed_field(alias="monitorBuyId")
    @property
    def monitor_buy_id(self) -> int:
        # 从 ORM 对象读取内部属性 id（或 _id）
        # 当使用 .model_validate(orm_obj) / model_validate 或 model_dump(from_attributes=True) 时会生效
        return getattr(self, "id")
    
    @computed_field(alias="startAt")
    @property
    def startAt(self) -> datetime:
        return self.createdAt

    @field_serializer("buyPrice")
    @property
    def convert_price_to_yuan(self, buy_price: int) -> str:
        return cents_to_yuan_str(buy_price)
    
    class Config:
        # 允许从 ORM 对象属性读取
        from_attributes = True